from jili.core.printlog import print
from jili.core.pymsg import mohe
import time
from functools import partial
"""
行情服务处理,支持外部消息中间件处理
priceserver:
1.参数值:可以是配置参数
参数配置:四个值;
{
recv_addrr='tcp://127.0.0.1:9114',
send_addrr='tcp://127.0.0.1:9115',#非必须,特殊情况下使用(行情服务端支持订阅的)
maxwokers=2,
isautorunrecv=True
}
2.直接是mohe对象;
3.recv_addrr地址
"""
class price:
    def __init__(self,priceserver,auto_stop=["16:20","16:30"],ischecktime=False,code_type="code"):
        self.send_msgtype = ("priceserver", "subprice")
        self.__ontickcall = {}
        self.tickkey = {}
        self.code_type=code_type
        if isinstance(priceserver,mohe):
            self.price_mohe=priceserver
        elif isinstance(priceserver,str):
            self.price_mohe=mohe(recv_addrr=priceserver)
        else:
            self.price_mohe=mohe(**priceserver)
        if auto_stop:
            self.price_mohe.set_auto_stop(auto_stop)
        self.__ontickcall_all= {}
        if ischecktime:
            self.__onallprice=self.__onallprice_True
            self.__onprice=self.__onprice_True
        else:
            self.__onallprice = self.__onallprice_False
            self.__onprice = self.__onprice_False
    def getprice_obj(self,p):
        if self.code_type in p.keys():
            obj = p[self.code_type]
        else:
            obj = p["obj"]
        return obj
    def __onallprice_True(self,dtype,msg):
        p = msg["2"]
        obj=self.getprice_obj(p)
        if dtype == "tick":
            if obj in self.tickkey.keys():
                if self.tickkey[obj] >= p["timekey"]:  # 去重  去老；只认最新行情
                    return None
            self.tickkey[obj] = p["timekey"]
        self.__ontickcall_all[dtype](p)
    def __onallprice_False(self,dtype,msg):
        p = msg["2"]
        self.__ontickcall_all[dtype](p)
    def run(self):
        if not self.price_mohe.isautorunrecv:
            self.price_mohe.run()
    def __onprice_True(self,dtype,msg):
        p = msg["2"]
        # print("debug",p)
        #p["timekey"] = datetime.datetime.strptime(p["timekey"], '%Y%m%d %H:%M:%S.%f')
        obj=self.getprice_obj(p)
        if dtype=="tick":
            if obj in self.tickkey.keys():
                if self.tickkey[obj] >= p["timekey"]:  # 去重  去老；只认最新行情
                    return None
            self.tickkey[obj] = p["timekey"]
        if dtype in self.__ontickcall.keys():
            if obj in self.__ontickcall[dtype].keys():
                for i in self.__ontickcall[dtype][obj]:
                    i(p)
    def __onprice_False(self,dtype,msg):
        p = msg["2"]
        # print("debug",p)
        obj=self.getprice_obj(p)
        if dtype in self.__ontickcall.keys():
            if obj in self.__ontickcall[dtype].keys():
                for i in self.__ontickcall[dtype][obj]:
                    i(p)
    def subtick(self,obj,dtype,oncall,info={}):
        if obj=="all":
            f=partial(self.__onallprice,dtype)
            self.__ontickcall_all[dtype]=oncall
            r=self.price_mohe.subscribe(f, dtype, "")
            print("subscribe监听全部设置", r, dtype, obj)
        else:
            f = partial(self.__onprice, dtype)
            if dtype not in self.__ontickcall.keys():
                self.__ontickcall[dtype]={}
            if obj not in self.__ontickcall[dtype].keys():
                self.__ontickcall[dtype][obj]=[]
            self.__ontickcall[dtype][obj].append(oncall)
            r=self.price_mohe.subscribe(f, dtype, obj)
            print("subscribe监听设置", r, dtype, obj)
            time.sleep(0.1)
            data = {"obj": obj,"dtype":dtype}
            data.update(info)
            r=self.price_mohe.send(self.send_msgtype[0], self.send_msgtype[1], data)
            print("send", r,self.send_msgtype, data)
            print("远程注册行情",obj)

    def unsubtick(self,obj,dtype,oncall=""):
        self.price_mohe.unsubscribe(oncall, dtype, obj)

def onprice(t):
    print("onprice",t)
if __name__ == '__main__':
    priceserver = {"recv_addrr":'tcp://127.0.0.1:80001',"send_addrr":'tcp://127.0.0.1:88001',"isautorunrecv":False}
    price_tick0=price(priceserver)
    price_tick0.subtick("all","tick",onprice)
    price_tick0.subtick("600000", "k1m", onprice)
    price_tick0.run()

